package com.example.greetingcard

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView

class HomeFragment : Fragment() {

    private lateinit var recyclerView: RecyclerView
    private lateinit var adapter: SimpleAdapter

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        val view = inflater.inflate(R.layout.home_fragment, container, false)
        recyclerView = view.findViewById(R.id.recyclerViewHome)

        // 设置布局管理器
        recyclerView.layoutManager = LinearLayoutManager(requireContext())

        // 准备数据
        val dataList = mutableListOf<String>()
        for (i in 1..20) {
            dataList.add("Item $i")
        }

        // 创建并设置适配器
        adapter = SimpleAdapter(dataList)
        recyclerView.adapter = adapter

        return view
    }


    private class SimpleAdapter(private val dataList: List<String>) :
        RecyclerView.Adapter<SimpleAdapter.SimpleViewHolder>() {

        inner class SimpleViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
            // 使用自定义布局中的 ID（假设为 item_text）
            val textView = itemView.findViewById<TextView>(R.id.item_text)  // 关键修改点
        }

        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): SimpleViewHolder {
            // 加载自定义布局（如 list_item_simple.xml）
            val view = LayoutInflater.from(parent.context)
                .inflate(R.layout.list_item_simple, parent, false)  // 关键修改点
            return SimpleViewHolder(view)
        }

        override fun onBindViewHolder(holder: SimpleViewHolder, position: Int) {
            holder.textView.text = dataList[position]  // 现在 textView 不再为 null
        }

        override fun getItemCount(): Int {
            return dataList.size
        }
    }
}

